import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// 重构后的proxy配置，支持从env中读取JSON格式的多代理配置
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  
  // 解析代理配置
  let proxyConfig = {}
  if (env.VITE_PROXY) {
    try {
      proxyConfig = JSON.parse(env.VITE_PROXY)
    } catch (e) {
      console.error('Error parsing VITE_PROXY:', e)
    }
  }

  return {
    base: env.NODE_ENV === 'production' ? '/static/' : '/',
    server: {
      proxy: proxyConfig
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
  }
})
